#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

using namespace std;

int main()
{
    // 创建子进程
    pid_t pid = fork();
    if (pid < 0)
    {
        perror("fork error");
        // 进程退出
        _exit(-1);
    }
    else if (pid == 0)
    {
        int cnt = 5;
        while (cnt--)
        {
            cout << "I am child process:"  << getpid() << endl;
            cout << "I am child, parent id:" << getppid() << endl;

            sleep(1);
        }   
        cout << "子进程结束执行" << endl;
        // 子进程结束
        _exit(0);
    }
    else
    {
        cout << "I am parent process:"  << getpid() << endl;
        cout << "I am parent, argument pid:"  << pid << endl;

        // 阻塞回收子进程资源
        // 子进程结束会解除阻塞
        wait(NULL);

        cout << "recycle resource completed." << endl;
    }

    while (1)
    {
        sleep(1);
    }

    return 0;
}